package com.liu.stockmarket.repository.database

import com.liu.stockmarket.repository.database.dao.StockDao
import com.liu.stockmarket.repository.database.dao.TransactionRecordDao
import com.liu.stockmarket.repository.database.entity.StockEntity
import kotlinx.coroutines.flow.Flow
import java.math.BigDecimal

class StockRepository(
    private val stockDao: StockDao,
    private val transactionRecordDao: TransactionRecordDao
) {

    /**
     * 股票，可转债
     */
    val allStock: Flow<List<StockEntity>> = stockDao.queryAllStock()

    /**
     * 持有 股票，可转债
     */
    val holdingStock: Flow<List<StockEntity>> = stockDao.queryHoldingStock()

    /**
     * 未持有股票(已清仓)
     */
    val noHoldingStock: Flow<List<StockEntity>> = stockDao.queryNoHoldingStock()

    /**
     * 持有 基金
     */
    val holdingFund: Flow<List<StockEntity>> = stockDao.queryHoldingFund()
    val allFund: Flow<List<StockEntity>> = stockDao.queryAllFund()

    /**
     * 未持有基金(已清仓)
     */
    val noHoldingFund: Flow<List<StockEntity>> = stockDao.queryNoHoldingFund()


    /**
     * 全部股票、基金、可转债
     */
    val all: Flow<List<StockEntity>> = stockDao.queryAllFlow()

    val allSelf = stockDao.querySelf()


    suspend fun save(stockEntity: StockEntity): Long {
        return stockDao.save(stockEntity)

    }

    fun queryByIdWithFlow(stockId: Long): Flow<StockEntity>? {
        return stockDao.queryByIdWithFlow(stockId)
    }

    suspend fun update(stockEntity: StockEntity) = stockDao.update(stockEntity)

    suspend fun queryById(id: Long): StockEntity? = stockDao.queryById(id)

    suspend fun queryByStockCode(stockCode: String) =
        stockDao.queryByStockCode(stockCode)

    /**
     * 删除股票，并删除关联的交易记录
     */
    suspend fun deleteStock(stockId: Long): Boolean {
        return if (stockDao.deleteById(stockId) > 0) {
            transactionRecordDao.deleteByStockId(stockId) > 0
        } else {
            false
        }
    }

    /**
     * 修改持仓价和数量
     */
    suspend fun modifyHoldingPriceAndNumber(
        stockId: Long,
        holdingPrice: BigDecimal,
        holdingNumber: BigDecimal
    ) = stockDao.modifyHoldingPriceAndNumber(stockId, holdingPrice, holdingNumber)

    suspend fun queryAllBuy() = stockDao.queryAllBuy()
    suspend fun queryAll() = stockDao.queryAll()

    suspend fun deleteAllForSaveAll(datas: List<StockEntity>) {
        stockDao.deleteAllForSaveAll(datas)
    }

    suspend fun deleteAll() {
        stockDao.deleteAll()
    }
}